<template>
  <div class="page-normal">
    <a-table
      id="sortTable"
      ref="tableRef"
      :columns="columns"
      :data-source="copyList"
      :pagination="false"
      :loading="loading"
      :scroll="{ x: 2100, scrollToFirstRowOnChange: true }"
      class="max-h-[75vh] overflow-y-scroll"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-if="column.key === 'icon_url'">
          <a-image
            width="37.6px"
            height="39.85px"
            class="w-[-webkit-fill-available] object-contain"
            :src="getIcon(record)"
            :fallback="defaultImage"
          />
        </template>
        <template v-else-if="column.key === 'name'">
          <a-tooltip placement="top" color="#fff" v-if="record.name">
            <template #title>
              {{ record.name }}
            </template>
            <div class="ellipsis-text">{{ record.name }}</div>
          </a-tooltip>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'create_at'">
          <span> {{ formatToDateTime(record.create_at * 1000) }} </span>
        </template>
        <template v-else-if="column.key === 'status'">
          <span>
            <a-switch
              v-model:checked="record.status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a style="color: #0083ff" @click="handleManage(record)">管理内容</a>
            <a-divider type="vertical" />
            <a style="color: #0083ff" @click="updateAd(record.id)">编辑</a>
            <a-divider type="vertical" />
            <a @click="deleteAd(record.id)" :class="type === 2 ? 'common-blue' : 'common-del'"> 删除 </a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 禁用对话框 -->
    <modal-view
      title="提示"
      v-model:visible="disabledVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="disableConfirm"
      @cancel="disableCancel"
    >
      <span>{{ type === 1 ? disabledText : activeText }}</span>
    </modal-view>
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>{{ deleteText }}</span>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { formatToDateTime } from '@/utils/format'
import { computed, onMounted, ref, toRefs, inject, nextTick } from 'vue'
import type { AdItem } from '@/types/advertising/advertising'
import ModalView from '@/components/components/modal/ModalView.vue'
import Sortable from 'sortablejs'
import { column } from '../dataSource'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import useStore from '@/stores'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import defaultImage from '@/assets/icon/defaultImage.png'
const tableRef = ref()
const baseUrl: any = inject('baseUrl')
const {
  advertising: { delete_library, update_status_library, library_order }
} = apis
const { permission } = useStore()
const router = useRouter()
interface SiteData {
  type: number | undefined
  list: AdItem[]
}
const props = defineProps<SiteData>()
let copyList = props.list
const activeText = ref('启用广告会获取该广告的应用内容，确定要启用该广告吗？')
const disabledText = ref('禁用广告库可能导致使用该广告库的应用停止广告展示，确定要禁用吗？')
const deleteText = ref('删除广告库不可恢复，可能导致使用该广告库的应用广告为空，确定要删除吗？')
const disabledVisible = ref(false)
const deleteVisible = ref(false)
const deleteId = ref()
const loading = ref(false)

const isChecked = ref(1) //是否禁用
const disabledId = ref() //禁用id
const emit = defineEmits(['update-list'])
const columns = ref(column)
const updateAd = (id: string) => {
  router.push({ name: 'EditAd', query: { id: id } })
}
/**
 * @description 删除
 * @param {id}
 */
const deleteAd = (id: string) => {
  deleteId.value = id
  if (props.type === 1) {
    return message.warning('启用中广告不能删除！')
  } else {
    deleteVisible.value = true
  }
}
/**
  删除广告对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  delete_library({ id: deleteId.value }).then((res: any) => {
    message.success('删除成功')
    deleteVisible.value = value
    emit('update-list')
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
//根据类型获取图片
const getIcon = computed(() => (item: AdItem) => {
  if (item.icon_type === 1) return baseUrl + item.icon_url
  return item.icon_url
})
//禁用确认取消
const disableConfirm = (value: any) => {
  console.log('value: ', value)
  const data = {
    status: isChecked.value,
    id: disabledId.value
  }
  console.log('data: ', data.id)
  update_status_library(data).then((res: any) => {
    message.success('禁用成功')
    disabledVisible.value = value
    emit('update-list')
  })
}
const disableCancel = () => {
  disabledVisible.value = false
  emit('update-list')
}
/** 修改站点禁用状态 */
const editStatus = (checked: number, row: AdItem) => {
  // console.log('row: ', checked, row.id)
  // const data = {
  //   status: checked,
  //   id: row.id
  // }
  // console.log('data: ', data.id)
  // update_status_library(data).then((res: any) => {
  //   message.success('修改成功')
  //   emit('update-list')
  // })
  if (props.type === 1) {
    disabledVisible.value = true
    isChecked.value = checked
    disabledId.value = row.id
  } else {
    const data = {
      status: checked,
      id: row.id
    }
    console.log('data: ', data.id)
    update_status_library(data).then((res: any) => {
      message.success('启用成功')
      emit('update-list')
    })
  }
}
const handleManage = (item: AdItem) => {
  nextTick(() => {
    console.log('item: ', item.name)
    permission.setSiteName(item.name)
    router.push({ name: 'StartAd' })
    storage.set('libraryId', item.id)
    permission.setSiderType('AD_BANK')
  })
}
//调用排序接口
const sortFunc = (item: any) => {
  loading.value = true
  library_order({
    ...item
  }).then(() => {
    message.success('排序成功')
    emit('update-list')
    loading.value = false
  })
}
//初始化表格拖动
const initSortable = () => {
  // const el = document.querySelector('#sortTable tbody') as HTMLElement
  const el = tableRef.value.table.$el.querySelector('#sortTable tbody') as HTMLElement
  console.log({ el })
  new Sortable(el, {
    handle: '.ant-table-row',
    animation: 150,
    ghostClass: 'blue-background-class',
    forceFallback: true,
    sort: true,
    // async
    onEnd(item) {
      console.log({ item })
      if (item.newIndex === item.oldIndex) return
      const startIndex = (item.oldIndex as number) - 1
      const endIndex = (item.newIndex as number) - 1
      const { id } = copyList[startIndex]
      const { order } = copyList[endIndex]
      sortFunc({ id, order })
    }
  })
}

onMounted(() => {
  initSortable()
})
</script>
<style lang="less" scoped>
.page-normal {
  height: 100%;
  :deep(.ant-table-cell):hover {
    cursor: pointer;
  }
  .common-blue {
    color: #0083ff;
  }

  .common-del {
    color: #bfbfbf;
  }
  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }
  :deep(.ant-table-body) {
    // min-height: 444px;
    // max-height: calc(100vh - 433px) !important;
    // overflow-y: scroll !important;
  }
  :deep(.ellipsis-text) {
    max-width: 170px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }
}
</style>
